# 创建新的岗位管理页面组件
<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>{{ pageTitle }}</h2>
    </div>

    <el-row :gutter="20">
      <!-- 左侧岗位信息表单 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-form :inline="true" class="search-form">
              <el-form-item label="所属部门">
                <el-select v-model="queryParams.deptId" placeholder="请选择部门" clearable style="width: 200px">
                  <el-option label="三支队一大队" value="1" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增岗位</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 岗位信息表单 -->
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="form.postName" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="所属部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择所属部门">
                <el-option label="三支队一大队" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="岗位类型" prop="postType">
              <el-select v-model="form.postType" placeholder="请选择岗位类型">
                <el-option
                  v-for="dict in dict.type.sys_post_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="岗位分类" prop="postCategory">
              <el-select v-model="form.postCategory" placeholder="请选择岗位分类">
                <el-option
                  v-for="dict in dict.type.sys_post_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="地点选择" prop="location">
              <el-radio-group v-model="form.locationType">
                <el-radio
                  v-for="dict in dict.type.sys_location_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="岗位位置" prop="location" v-if="form.locationType === 1">
              <el-input v-model="form.location" placeholder="请选择岗位位置" :readonly="pageMode==='detail'" :disabled="pageMode==='detail'" @focus="handleLocationSelect" />
            </el-form-item>
            <el-form-item label="有效时间" prop="validTime">
              <el-date-picker
                v-model="form.validTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="班次设置" prop="shifts">
              <el-button type="primary" size="small" @click="showShifts = !showShifts">
                {{ showShifts ? '隐藏班次信息' : '显示班次信息' }}
              </el-button>
            </el-form-item>
            <div v-if="showShifts">
              <el-form-item label="" prop="shifts" class="shift-container">
                <div v-if="!form.shifts || form.shifts.length === 0" class="no-data-tip">
                  暂无班次信息，请点击下方按钮添加班次
                </div>
                <el-table v-else :data="form.shifts" border style="width: 100%">
                  <el-table-column label="班次类型" align="center" width="150">
                    <template slot-scope="scope">
                      <span v-if="pageMode === 'detail'">{{ getShiftTypeLabel(scope.row.type) }}</span>
                      <el-select v-else v-model="scope.row.type" placeholder="请选择" size="mini">
                        <el-option
                          v-for="dict in dict.type.sys_shift_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="时间段" align="center">
                    <template slot-scope="scope">
                      <span v-if="pageMode === 'detail'">
                        {{ scope.row.startTime || '-' }} 至 {{ scope.row.endTime || '-' }}
                      </span>
                      <template v-else>
                        <el-time-picker
                          v-model="scope.row.startTime"
                          size="mini"
                          placeholder="开始时间"
                          value-format="HH:mm:ss"
                          style="width: 110px;">
                        </el-time-picker>
                        <span style="margin: 0 5px">至</span>
                        <el-time-picker
                          v-model="scope.row.endTime"
                          size="mini"
                          placeholder="结束时间"
                          value-format="HH:mm:ss"
                          style="width: 110px;">
                        </el-time-picker>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" size="mini" @click="handleDeleteShift(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button style="margin-top: 10px" type="text" @click="handleAddShift">+ 新增班次</el-button>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="submitForm" v-if="pageMode !== 'detail'">保存岗位</el-button>
              <el-button @click="resetForm" v-if="pageMode !== 'detail'">重置</el-button>
              <el-button @click="goBack">返回</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧地图区域 -->
      <el-col :span="16">
        <el-card class="box-card">
          <div class="map-container" ref="mapContainer"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { addPost, updatePost, getPost, savePostWithShifts, addPostWithShifts } from "@/api/system/post";

export default {
  name: 'PatrolPost',
  dicts: ['sys_post_type', 'sys_post_category', 'sys_location_type', 'sys_shift_type'],
  data() {
    // 自定义班次验证规则
    const validateShifts = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请至少添加一个班次'));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 地图实例
      map: null,
      // 当前标记点
      currentMarker: null,
      // 页面模式：add-新增, edit-编辑, detail-详情
      pageMode: 'add',
      // 查询参数
      queryParams: {
        deptId: undefined
      },
      // 日期选择器快捷选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 是否显示班次信息
      showShifts: false,
      // 表单参数
      form: {
        postName: undefined,
        deptId: undefined,
        postType: undefined,
        postCategory: undefined,
        locationType: 1,
        location: undefined,
        position: undefined,
        validTime: [],
        shifts: [],
        id: undefined
      },
      // 表单校验
      rules: {
        postName: [
          { required: true, message: '岗位名称不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        postType: [
          { required: true, message: '请选择岗位类型', trigger: 'change' }
        ],
        postCategory: [
          { required: true, message: '请选择岗位分类', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请选择岗位位置', trigger: 'change' }
        ],
        validTime: [
          { required: true, message: '请选择有效时间', trigger: 'change' }
        ],
        shifts: [
          { required: true, validator: validateShifts, trigger: 'change' }
        ]
      },
      // 图标配置
      markerIcons: {
        '1': require('@/assets/images/收费站.png'),
        '2': require('@/assets/images/服务点.png')
      }
    };
  },
  computed: {
    pageTitle() {
      const titles = {
        'add': '新增岗位',
        'edit': '编辑岗位',
        'detail': '岗位详情'
      };
      return titles[this.pageMode] || '岗位管理';
    }
  },
  mounted() {
    this.initMap();
    this.parseRouteParams();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    async initMap() {
      try {
        const AMap = await AMapLoader.load({
          key: '4b98d24146ee2f4b43cc046b7886cb71',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation']
        });

        // 创建地图实例
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 12,
          center: [114.085947, 22.547], // 深圳市中心坐标
          viewMode: '3D'
        });

        // 添加地图控件
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.HawkEye({isOpen: true}));
        this.map.addControl(new AMap.MapType());
        this.map.addControl(new AMap.Geolocation());

        // 点击地图事件
        this.map.on('click', (e) => {
          if (this.form.locationType === 1) {
            this.handleMapClick(e);
          }
        });
      } catch (e) {
        console.error('地图加载失败', e);
      }
    },
    // 检查班次数据是否正确
    checkShiftsData() {
      if (!this.form.shifts) {
        console.warn("班次数据为null或undefined，初始化为空数组");
        this.form.shifts = [];
        return false;
      }
      
      if (!Array.isArray(this.form.shifts)) {
        console.warn("班次数据不是数组，转换为空数组");
        this.form.shifts = [];
        return false;
      }
      
      if (this.form.shifts.length === 0) {
        console.log("班次数据为空数组");
        return false;
      }
      
      // 检查每个班次对象是否有正确的属性
      for (let i = 0; i < this.form.shifts.length; i++) {
        const shift = this.form.shifts[i];
        if (!shift.type || !shift.startTime || !shift.endTime) {
          console.warn(`第${i+1}个班次数据不完整:`, shift);
        }
      }
      
      console.log("班次数据有效:", this.form.shifts);
      return true;
    },
    // 处理地图点击
    handleMapClick(e) {
      const position = e.lnglat;
      this.form.position = [position.getLng(), position.getLat()];
      // 岗位位置直接显示经纬度
      this.form.location = `${position.getLng()},${position.getLat()}`;

      // 更新标记点
      if (this.currentMarker) {
        this.currentMarker.setMap(null);
      }

      // 根据岗位分类选择图标
      const iconPath = this.markerIcons[this.form.postCategory] || require('@/assets/images/marker.png');

      this.currentMarker = new AMap.Marker({
        position: position,
        icon: new AMap.Icon({
          size: new AMap.Size(32, 32),
          image: iconPath,
          imageSize: new AMap.Size(32, 32)
        }),
        offset: new AMap.Pixel(-16, -16)
      });
      this.currentMarker.setMap(this.map);
    },
    // 监听岗位分类变化
    handlePostCategoryChange() {
      if (this.currentMarker && this.form.position) {
        // 更新现有标记点的图标
        const iconPath = this.markerIcons[this.form.postCategory] || require('@/assets/images/marker.png');
        this.currentMarker.setIcon(new AMap.Icon({
          size: new AMap.Size(32, 32),
          image: iconPath,
          imageSize: new AMap.Size(32, 32)
        }));
      }
    },
    // 新增岗位
    handleAdd() {
      this.pageMode = 'add';
      this.resetForm();
      // 清除路由参数
      this.$router.replace({ path: '/patrol/post', query: { mode: 'add' }});
    },
    // 获取班次类型的标签
    getShiftTypeLabel(value) {
      if (!value) return '';
      
      // 从字典获取标签
      const dict = this.dict.type.sys_shift_type || [];
      const item = dict.find(d => d.value === value);
      return item ? item.label : value;
    },
    // 新增班次
    handleAddShift() {
      const newShift = {
        type: '',
        startTime: '',
        endTime: ''
      };
      this.form.shifts.push(newShift);
      console.log('新增班次:', newShift, '当前所有班次:', this.form.shifts);
    },
    // 删除班次
    handleDeleteShift(index) {
      this.$confirm('是否确认删除该班次?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('删除班次前:', this.form.shifts);
        this.form.shifts.splice(index, 1);
        console.log('删除班次后:', this.form.shifts);
        this.$message.success('删除成功');
      }).catch(() => {});
    },
    // 选择位置
    handleLocationSelect() {
      this.$message.info('请在地图上点击选择位置');
    },
    // 提交表单
    async submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          try {
            console.log("表单验证通过，准备提交数据");
            
            // 验证班次信息的完整性
            if (this.form.shifts.length === 0) {
              this.$modal.msgError('请至少添加一个班次');
              return;
            }

            console.log("当前班次数据:", this.form.shifts);
            
            // 验证每个班次的必填信息
            for (const shift of this.form.shifts) {
              if (!shift.type) {
                this.$modal.msgError('请选择班次类型');
                return;
              }
              if (!shift.startTime) {
                this.$modal.msgError('请选择班次开始时间');
                return;
              }
              if (!shift.endTime) {
                this.$modal.msgError('请选择班次结束时间');
                return;
              }
            }

            // 构建提交数据
            const postData = {
              id: this.form.id,
              postName: this.form.postName,
              department: this.form.deptId,
              postType: this.form.postType,
              postCategory: this.form.postCategory,
              locationType: this.form.locationType,
              postLocation: this.form.location,
              longitude: this.form.position ? this.form.position[0] : null,
              latitude: this.form.position ? this.form.position[1] : null,
              validDate: this.form.validTime ? this.form.validTime.join(',') : null,
              shifts: this.form.shifts.map(shift => {
                // 构建符合后端要求的班次数据格式
                const shiftData = {
                  shiftName: shift.type,
                  shiftTimePeriod: `${shift.startTime}-${shift.endTime}`,
                  isEnabled: 1,
                  // 如果是已存在的班次，保留ID
                  postId: this.form.id
                };
                
                if (shift.id) {
                  shiftData.id = shift.id;
                }
                
                return shiftData;
              })
            };

            console.log("准备提交的岗位数据:", JSON.stringify(postData));

            try {
              // 根据页面模式调用不同的API
              if (this.pageMode === 'add') {
                console.log("提交新增岗位数据:", postData);
                const result = await addPostWithShifts(postData);

                if (result && result.code === 200) {
                  this.$modal.msgSuccess('岗位及班次保存成功');
                  // 保存成功后跳转到岗位列表页
                  this.$router.push('/patrol/index');
                } else {
                  throw new Error(result?.msg || '岗位信息保存失败');
                }
              } else if (this.pageMode === 'edit') {
                console.log("提交编辑岗位数据:", postData);
                const result = await savePostWithShifts(postData);

                if (result && result.code === 200) {
                  this.$modal.msgSuccess('岗位信息更新成功');
                  // 保存成功后跳转到岗位列表页
                  this.$router.push('/patrol/index');
                } else {
                  throw new Error(result?.msg || '岗位信息更新失败');
                }
              }
            } catch (error) {
              console.error("保存岗位及班次失败:", error);
              this.$modal.msgError('保存失败: ' + error.message);
              return;
            }
          } catch (error) {
            console.error('保存失败:', error);
            this.$modal.msgError('保存失败：' + (error.message || '未知错误'));
          }
        }
      });
    },
    // 重置表单
    resetForm() {
      this.form = {
        postName: undefined,
        deptId: undefined,
        postType: undefined,
        postCategory: undefined,
        locationType: 1,
        location: undefined,
        position: undefined,
        validTime: [],
        shifts: [],
        id: undefined
      };
      this.showShifts = false;
      if (this.currentMarker) {
        this.currentMarker.setMap(null);
        this.currentMarker = null;
      }
      this.$refs['form'].resetFields();
    },
    // 解析路由参数
    parseRouteParams() {
      const { mode, id } = this.$route.query;
      this.pageMode = mode || 'add';
      
      // 确保初始化班次数组
      if (!this.form.shifts) {
        this.form.shifts = [];
      }
      
      if (mode === 'edit' || mode === 'detail') {
        if (id) {
          this.getPostDetail(id);
        } else {
          this.$message.error('缺少岗位ID参数');
          this.$router.push('/patrol');
        }
      }
    },
    // 获取岗位详情
    async getPostDetail(id) {
      try {
        this.loading = true;
        const response = await getPost(id);
        console.log("获取岗位详情返回数据:", response);
        
        if (response.code === 200) {
          // 从response.data中获取岗位信息
          let postData = response.data;
          console.log("岗位详情数据:", postData);
          
          // 填充表单数据
          this.form = {
            id: postData.id,
            postName: postData.postName,
            deptId: postData.department,
            postType: postData.postType,
            postCategory: postData.postCategory,
            locationType: postData.locationType || 1,
            // 岗位位置直接显示经纬度
            location: (postData.longitude && postData.latitude) ? `${postData.longitude},${postData.latitude}` : '',
            position: postData.longitude && postData.latitude ? [postData.longitude, postData.latitude] : undefined,
            validTime: postData.validDate ? postData.validDate.split(',') : [],
            shifts: []
          };
          
          // 直接从岗位数据中获取班次信息
          if (postData.shifts && Array.isArray(postData.shifts)) {
            console.log("从岗位数据中获取班次信息:", JSON.stringify(postData.shifts));
            
            this.form.shifts = postData.shifts.map(shift => ({
              id: shift.id,
              type: shift.shiftName,
              startTime: shift.shiftTimePeriod ? shift.shiftTimePeriod.split('-')[0] : '',
              endTime: shift.shiftTimePeriod ? (shift.shiftTimePeriod.split('-')[1] || '') : ''
            }));
            
            console.log("处理后的班次数据:", JSON.stringify(this.form.shifts));
            
            if (this.form.shifts.length > 0) {
              this.showShifts = true;
            }
          }
          
          // 如果是详情模式，禁用表单并始终显示班次信息
          if (this.pageMode === 'detail') {
            this.disableForm();
            this.showShifts = true;
          }
          
          // 如果有位置信息，在地图上显示标记
          if (this.form.position && this.map) {
            this.showMarkerOnMap();
          }
        } else {
          this.$message.error('获取岗位详情失败');
        }
      } catch (error) {
        console.error('获取岗位详情失败:', error);
        this.$message.error('获取岗位详情失败');
      } finally {
        this.loading = false;
      }
    },
    // 在地图上显示标记
    showMarkerOnMap() {
      if (this.currentMarker) {
        this.currentMarker.setMap(null);
      }

      const position = new AMap.LngLat(this.form.position[0], this.form.position[1]);
      const iconPath = this.markerIcons[this.form.postCategory] || require('@/assets/images/marker.png');

      this.currentMarker = new AMap.Marker({
        position: position,
        icon: new AMap.Icon({
          size: new AMap.Size(32, 32),
          image: iconPath,
          imageSize: new AMap.Size(32, 32)
        }),
        offset: new AMap.Pixel(-16, -16)
      });
      this.currentMarker.setMap(this.map);

      // 将地图中心移动到标记位置
      this.map.setCenter(position);
    },
    // 禁用表单（详情模式）
    disableForm() {
      // 禁用所有输入框
      const formElements = this.$refs.form.$el.querySelectorAll('input, select, textarea');
      formElements.forEach(element => {
        element.disabled = true;
      });

      // 隐藏操作按钮
      this.$nextTick(() => {
        const submitButtons = this.$refs.form.$el.querySelectorAll('.el-button');
        submitButtons.forEach(button => {
          button.style.display = 'none';
        });
      });
    },
    // 返回按钮
    goBack() {
      this.$router.push('/patrol');
    }
  },
  watch: {
    'form.postCategory': {
      handler: 'handlePostCategoryChange',
      immediate: false
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .page-header {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .search-form {
    margin-bottom: 10px;
  }
  
  .map-container {
    height: 800px;
    width: 100%;
    border-radius: 4px;
    overflow: hidden;
  }

  .box-card {
    margin-bottom: 20px;
  }
  
  .shift-container {
    margin-left: 20px;
    padding: 15px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    background-color: #f9f9f9;
  }
  
  .no-data-tip {
    padding: 20px;
    text-align: center;
    color: #909399;
    font-size: 14px;
  }
}
</style>
